package com.ErpCoreWeb.Report;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Report.CReport;
import com.ErpCoreModel.Report.CStatItem;
import com.ErpCoreModel.Report.enumItemType;
import com.ErpCoreModel.Report.enumOrder;
import com.ErpCoreModel.Report.enumStatType;
import com.ErpCoreWeb.Common.EditObject;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class RunReport
 */
@WebServlet("/RunReport")
public class RunReport extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CTable m_Table = null;
    public CCompany m_Company = null;
    public CReport m_Report = null; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RunReport() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
		try {

			String RPT_Reprot_id = request.getParameter("id");
	        if (Global.IsNullParameter(RPT_Reprot_id))
	        {
	            response.getWriter().close();
	            return;
	        }

	        String B_Company_id = request.getParameter("B_Company_id");
			if (Global.IsNullParameter(B_Company_id))
				m_Company = Global.GetCtx(this.getServletContext())
						.getCompanyMgr().FindTopCompany();
			else
				m_Company = (CCompany) Global.GetCtx(this.getServletContext())
						.getCompanyMgr().Find(Util.GetUUID(B_Company_id));
			
	        m_Table = (CTable)m_Company.getReportMgr().getTable();

	        m_Report = (CReport)m_Company.getReportMgr().Find(Util.GetUUID(RPT_Reprot_id));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
	}
    public List<CStatItem> GetStatItemList()
    {
        List<CStatItem> lstStatItem = new ArrayList<CStatItem>();
        List<CBaseObject> lstObj = m_Report.getStatItemMgr().GetList();
        for (CBaseObject obj : lstObj)
        {
            lstStatItem.add((CStatItem)obj);
        }
        Collections.sort(lstStatItem, new Comparator() {
			public int compare(Object a, Object b) {
				return ((CStatItem) a).getIdx() - ((CStatItem) b).getIdx();
			}
		});
        return lstStatItem;
    }
    void GetData()
    {

        List<CStatItem> lstStatItem = GetStatItemList();


        List<String> lstTable = new ArrayList<String>();
        String sFields = "";
        String sGroupBy = "";
        String sOrderBy = "";
        for (CStatItem StatItem : lstStatItem)
        {
        	String sOrderFiled = "";
            if (StatItem.getItemType() == enumItemType.Field)
            {
                CTable table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(StatItem.getFW_Table_id());
                if (table == null)
                    continue;
                CColumn column = (CColumn)table.getColumnMgr().Find(StatItem.getFW_Column_id());
                if (column == null)
                    continue;

                if (!lstTable.contains(table.getCode()))
                    lstTable.add(table.getCode());
                if (StatItem.getStatType() == enumStatType.Val)
                {
                    sFields += String.format("[%s].[%s],", table.getCode(), column.getCode());
                    sGroupBy += String.format("[%s].[%s],", table.getCode(), column.getCode());
                    sOrderFiled = String.format("[%s].[%s]", table.getCode(), column.getCode());
                }
                else
                {
                    sFields += String.format("%s([%s].[%s]) as [%s],",
                        StatItem.GetStatTypeFunc(), table.getCode(), column.getCode(), StatItem.getName());
                    sOrderFiled = StatItem.getName();
                }
            }
            else
            {
                sFields += String.format("(%s) as [%s],", StatItem.getFormula(), StatItem.getName());
                sOrderFiled = StatItem.getName();
            }

            if (StatItem.getOrder() == enumOrder.Asc)
                sOrderBy += sOrderFiled + ",";
            else if (StatItem.getOrder() == enumOrder.Desc)
                sOrderBy += sOrderFiled + " desc,";
        }
        if(sFields.length()>0 && sFields.endsWith(","))
        	sFields = sFields.substring(0, sFields.length()-1);
        if(sGroupBy.length()>0 && sGroupBy.endsWith(","))
        	sGroupBy = sGroupBy.substring(0, sGroupBy.length()-1);
        if(sOrderBy.length()>0 && sOrderBy.endsWith(","))
        	sOrderBy = sOrderBy.substring(0, sOrderBy.length()-1);

        String sTable = "";
        for (String sTb : lstTable)
        {
            sTable += sTb + ",";
        }
        if(sTable.length()>0 && sTable.endsWith(","))
        	sTable = sTable.substring(0, sTable.length()-1);

        String sSql = String.format("select {0} from {1} ", sFields, sTable);
        sSql += " where IsDeleted=0 ";
        if (m_Report.getFilter().trim().length()>0)
            sSql += " and " + m_Report.getFilter();
        if (sGroupBy .length()>0)
            sSql += " group by " + sGroupBy;
        if (sOrderBy .length()>0)
            sSql += " order by " + sOrderBy;

        //因为采用构造sql语句的方法来运行报表，所以仅考虑单数据库的情况，
        //即取主数据库。如果考虑多数据库分布存储情况，则使用对象来计算报表。
        ResultSet rs = Global.GetCtx(this.getServletContext()).getMainDB().Query(sSql);
        if (rs == null)
        {
            //MessageBox.Show("运行报表失败，请修改报表定义！");
            return;
        }


        String sData = "";

        int iRowCount=0;
        try {
			while (rs.next())
			{
			    String sRow = "";
			    int iCol = 0;
			    for (CStatItem StatItem : lstStatItem)
			    {
			        String sVal="";
					try {
						sVal = rs.getObject(iCol).toString();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        sRow += String.format("\"%s\":\"%s\",", StatItem.getName(), sVal);
			        iCol++;
			    }

			    if(sRow.length()>0 && sRow.endsWith(","))
			    	sRow = sRow.substring(0, sRow.length()-1);
			    sRow = "{" + sRow + "},";
			    sData += sRow;
			    
			    iRowCount++;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if(sData.length()>0 && sData.endsWith(","))
        	sData = sData.substring(0, sData.length()-1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iRowCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
